layui.define(['jquery', 'form'], function(exports){
    var $ = layui.jquery, form = layui.form();
    var url = "/shop/api/area?parentId=";
    var pid = 0;

    $.post(url+'0&level=1', function(rs){
        var str = "";
        $.each(rs.data, function(i,item){
            str += '<option value="' + item.id + '"';
            // if(item.name.indexOf('四川') == 0){
            //     str += 'checked';
            //     pid = item.id;
            // }
            str += '>'+ item.name +'</option>';
        });
        $("#pId").html(str);
        //initSelectData(pid);
        // $('#cityId').show();
        form.render();
    });

    function initSelectData(val){
        val = val || $('#pId').val()
        $.post(url+val+'&level=2', function(rs){
            var str = "<option value=''></option>", pid = 0;
            $.each(rs.data, function(i,item){
                str += '<option value="' + item.id + '"';

                str += '>'+ item.name +'</option>';
            });
            $("select[name='a.city_id']").html(str);
            test2(pid);
        });
    }

    function test2(val){
        val = val || $('#cityId').val()
        $.post(url+val+'&level=3', function(rs){
            var str = "<option value=''></option>";
            $.each(rs.data, function(i,item){
                str += '<option value="' + item.id + '"';
                str += '>'+ item.name +'</option>';
            });
           $("select[name='a.district_id']").html(str);
           form.render();
        });
    }
    form.on('select(p1)', function(data){
        var val = data.value;
        $.post(url+val+'&level=2', function(rs){
            var str = "";
            $.each(rs.data, function(i,item){
                str += '<option value="' + item.id + '"';
                str += '>'+ item.name +'</option>';
            });
            $("select[name='a.city_id']").html(str);
            form.render();
        });
    });

    form.on('select(city)', function(data){
        test2(data.value);
    });

    form.on('select(district)', function(data){
        $('#desc').show();
    });
    exports('area_select', {});
});